import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class AnswerRecordDAO {

    public boolean saveAnswer(int examRecordId, int questionId, String answerText, double score) {
        String sql = "INSERT INTO answer_records (exam_record_id, question_id, answer_text, score) VALUES (?, ?, ?, ?) "
                +
                "ON DUPLICATE KEY UPDATE answer_text = VALUES(answer_text), score = VALUES(score)";

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, examRecordId);
            stmt.setInt(2, questionId);
            stmt.setString(3, answerText);
            stmt.setDouble(4, score);

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getAnswer(int examRecordId, int questionId) {
        String sql = "SELECT answer_text FROM answer_records WHERE exam_record_id = ? AND question_id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, examRecordId);
            stmt.setInt(2, questionId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getString("answer_text");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<AnswerRecord> getAnswersByExamRecord(int examRecordId) {
        List<AnswerRecord> answers = new ArrayList<>();
        String sql = "SELECT * FROM answer_records WHERE exam_record_id = ? ORDER BY question_id";

        System.out.println("=== 获取答案记录 ===");
        System.out.println("examRecordId: " + examRecordId);

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, examRecordId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                AnswerRecord answer = new AnswerRecord();
                answer.setId(rs.getInt("id"));
                answer.setExamRecordId(rs.getInt("exam_record_id"));
                answer.setQuestionId(rs.getInt("question_id"));
                answer.setAnswerText(rs.getString("answer_text"));
                answer.setScore(rs.getDouble("score"));
                answers.add(answer);

                System.out.println("从数据库读取答案记录: ID=" + answer.getId() +
                        ", questionId=" + answer.getQuestionId() +
                        ", score=" + answer.getScore());
            }

            System.out.println("总共获取到 " + answers.size() + " 条答案记录");
        } catch (SQLException e) {
            System.out.println("获取答案记录时发生SQL错误: " + e.getMessage());
            e.printStackTrace();
        }
        return answers;
    }

    public double calculateAutoGradeScore(int questionId, String answerText) {
        QuestionDAO questionDAO = new QuestionDAO();
        Question question = questionDAO.getQuestionById(questionId);

        if (question == null) {
            return 0.0;
        }

        String questionType = question.getQuestionType();

        if ("single_choice".equals(questionType) || "multiple_choice".equals(questionType)) {
            return gradeChoiceQuestion(question, answerText);
        } else if ("true_false".equals(questionType)) {
            return gradeTrueFalseQuestion(question, answerText);
        } else if ("fill_blank".equals(questionType)) {
            return gradeFillBlankQuestion(question, answerText);
        } else {
            // 问答题需要人工评分
            return 0.0;
        }
    }

    private double gradeChoiceQuestion(Question question, String answerText) {
        if (answerText == null || answerText.trim().isEmpty()) {
            return 0.0;
        }

        List<QuestionOption> options = question.getOptions();
        if (options == null || options.isEmpty()) {
            return 0.0;
        }

        // 单选题
        if ("single_choice".equals(question.getQuestionType())) {
            for (QuestionOption option : options) {
                if (option.getOptionLabel().equals(answerText.trim()) && option.isCorrect()) {
                    return question.getScore();
                }
            }
            return 0.0;
        }

        // 多选题（简化处理：答案完全正确才得分）
        if ("multiple_choice".equals(question.getQuestionType())) {
            String[] selectedOptions = answerText.split(",");
            List<String> correctOptions = new ArrayList<>();

            for (QuestionOption option : options) {
                if (option.isCorrect()) {
                    correctOptions.add(option.getOptionLabel());
                }
            }

            if (selectedOptions.length == correctOptions.size()) {
                for (String selected : selectedOptions) {
                    if (!correctOptions.contains(selected.trim())) {
                        return 0.0;
                    }
                }
                return question.getScore();
            }
            return 0.0;
        }

        return 0.0;
    }

    private double gradeTrueFalseQuestion(Question question, String answerText) {
        if (answerText == null || answerText.trim().isEmpty()) {
            return 0.0;
        }

        String correctAnswer = question.getCorrectAnswer();
        if (correctAnswer == null) {
            return 0.0;
        }

        // 判断题评分：答案完全匹配才得分
        if (correctAnswer.equals(answerText.trim())) {
            return question.getScore();
        }

        return 0.0;
    }

    private double gradeFillBlankQuestion(Question question, String answerText) {
        if (answerText == null || answerText.trim().isEmpty()) {
            return 0.0;
        }

        String correctAnswer = question.getCorrectAnswer();
        if (correctAnswer == null || correctAnswer.trim().isEmpty()) {
            // 如果没有标准答案，给部分分数（需要人工评分）
            return question.getScore() * 0.5;
        }

        // 填空题评分：可以进行模糊匹配或完全匹配
        String studentAnswer = answerText.trim().toLowerCase();
        String standardAnswer = correctAnswer.trim().toLowerCase();

        if (standardAnswer.equals(studentAnswer)) {
            return question.getScore();
        }

        // 可以添加更复杂的匹配逻辑，比如包含关键词等
        if (standardAnswer.contains(studentAnswer) || studentAnswer.contains(standardAnswer)) {
            return question.getScore() * 0.8; // 部分正确给80%分数
        }

        return 0.0;
    }

    public boolean updateAnswerScore(int examRecordId, int questionId, double score) {
        String sql = "UPDATE answer_records SET score = ? WHERE exam_record_id = ? AND question_id = ?";

        System.out.println("=== 更新答案分数 ===");
        System.out.println("examRecordId: " + examRecordId);
        System.out.println("questionId: " + questionId);
        System.out.println("new score: " + score);

        try (Connection conn = DatabaseConnection.getConnection();
                PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setDouble(1, score);
            stmt.setInt(2, examRecordId);
            stmt.setInt(3, questionId);

            int rowsUpdated = stmt.executeUpdate();
            System.out.println("更新的行数: " + rowsUpdated);

            if (rowsUpdated > 0) {
                System.out.println("分数更新成功！");
                return true;
            } else {
                System.out.println("警告：没有找到匹配的记录进行更新！");
                return false;
            }
        } catch (SQLException e) {
            System.out.println("更新分数时发生SQL错误: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
}

// 答案记录实体类
class AnswerRecord {
    private int id;
    private int examRecordId;
    private int questionId;
    private String answerText;
    private double score;

    // Getters and Setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getExamRecordId() {
        return examRecordId;
    }

    public void setExamRecordId(int examRecordId) {
        this.examRecordId = examRecordId;
    }

    public int getQuestionId() {
        return questionId;
    }

    public void setQuestionId(int questionId) {
        this.questionId = questionId;
    }

    public String getAnswerText() {
        return answerText;
    }

    public void setAnswerText(String answerText) {
        this.answerText = answerText;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}